﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace 在XAML中调用库
{
    public class MyDependencyObject:DependencyObject
    {
        public int Value
        {
            get { return (int)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }
        /// <summary>
        /// 创建属性的依赖关系
        /// </summary>
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register(nameof(Value), typeof(int), typeof(MyDependencyObject),
                new PropertyMetadata(0,OnValueChanged,CoerceValue));
        /// <summary>
        /// 读取新旧值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="e"></param>
        private static void OnValueChanged(DependencyObject obj,DependencyPropertyChangedEventArgs e)
        {
            int oldValue = (int)e.OldValue;
            int newValue = (int)e.NewValue;
        }
        /// <summary>
        /// 对值进行强制检查，
        /// 属性值的每次变更均会调用
        /// 保证值在最大最小值的范围内
        /// </summary>
        /// <param name="d"></param>
        /// <param name="baseValue"></param>
        /// <returns></returns>
        private static object CoerceValue(DependencyObject d,object baseValue)
        {
            int newValue = (int)baseValue;

            MyDependencyObject control = (MyDependencyObject)d;
            //
            newValue = Math.Max(control.Minimum, Math.Min(control.Maximum, newValue));

            return newValue;
        } 

        public int Minimum
        {
            get { return (int)GetValue(MinimumProperty); }
            set { SetValue(MinimumProperty,value); }
        }
        public static readonly DependencyProperty MinimumProperty =
            DependencyProperty.Register(nameof(Minimum), typeof(int),
                typeof(MyDependencyObject), new PropertyMetadata(0));

        public int Maximum
        {
            get { return (int)GetValue(MaximumProperty); }
            set { SetValue(MaximumProperty, value); }
        }
        public static readonly DependencyProperty MaximumProperty =
            DependencyProperty.Register(nameof(Maximum), typeof(int),
                typeof(MyDependencyObject), new PropertyMetadata(100));

    }
}
